package com.voodoo.lib_frame.base;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkCapabilities;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.voodoo.lib_frame.Config;
import com.voodoo.lib_frame.R;
import com.voodoo.lib_frame.manager.ActivityManager;
import com.voodoo.lib_frame.toast.Toast;
import com.voodoo.lib_frame.utils.ScreenUtils;

import butterknife.ButterKnife;

/**
 * Author: voodoo
 * CreateDate: 2021/05/16
 * Description: 所有Activity的基类
 */
public abstract class BaseActivity extends AppCompatActivity {

    FrameLayout contentFlayout; // 所有控件的父布局
    ProgressDialog progressDialog;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN); // 设置软键盘不遮挡布局
        setContentView(R.layout.activity_base);
        ActivityManager.getInstance().addActivity(this);
        setBaseView(getLayoutResId()); // 设置加载的布局
        ButterKnife.bind(this); // 注入绑定Activity
        initViews();
        initData();
    }

    /**
     * 设置共有的界面展示View
     *
     * @param layoutResId 布局资源文件的ID
     */
    private void setBaseView(int layoutResId) {

        // 设置沉浸式状态栏
        if (Config.isImmersiveStatusBar) {
            ScreenUtils.setImmersiveStatusBar(this);
        }

        // 获取布局资源文件
        contentFlayout = findViewById(R.id.baseActivity_content_flayout);
        LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View rootView = inflater.inflate(layoutResId, null);
        rootView.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT));
        contentFlayout.addView(rootView);

    }

    /**
     * 设置加载的布局文件
     *
     * @return 加载的资源文件ID
     */
    protected abstract int getLayoutResId();

    /**
     * 初始化View，设置显隐或初始黄台
     */
    protected abstract void initViews();

    /**
     * 初始化界面的数据
     */
    protected abstract void initData();

    // ==================================================================================== 界面跳转


    /**
     * 带订单信息的跳转
     *
     * @param mClass
     * @param json
     */
    public void doStartActivity(Class mClass, String json) {
        Bundle bundle = new Bundle();
        bundle.putString("shopOrderBean", json);
        startActivity(mClass, bundle);
        finish();
    }

    /**
     * 跳转界面
     *
     * @param clazz  目标界面
     * @param bundle 携带的参数，若无参数可传，则直接放置null即可
     */
    protected void startActivity(Class<?> clazz, Bundle bundle) {
        Intent intent = new Intent(this, clazz);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        startActivity(intent);
    }

    /**
     * 带返回数据的跳转，自行实现 {@link #onActivityResult(int, int, Intent)}
     *
     * @param clazz       目标Activity
     * @param bundle      携带的参数，若无参数可传，则直接放置null即可
     * @param requestCode 请求码
     */
    protected void startActivityForResult(Class<?> clazz, Bundle bundle, int requestCode) {
        Intent intent = new Intent(this, clazz);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        startActivityForResult(intent, requestCode);
    }

    // ======================================================================================= Click

    /**
     * View的点击事件
     *
     * @param view 点击的View
     */
    public void onClick(View view) {
    }

    // ======================================================================================= Toast

    /**
     * 展示 Toast 消息提示
     *
     * @param showMsg 展示信息
     */
    protected void showToast(String showMsg) {
        Toast.showXToast(this, showMsg);
    }

    /**
     * 展示 Toast 消息提示
     *
     * @param showMsg  展示信息
     * @param duration 展示Toast的时间长短，取值：{@code Toast.LENGTH_SHORT}(2s)、{@code Toast.LENGTH_LONG}(3.5s)
     */
    protected void showToast(String showMsg, int duration) {
        Toast.showXToast(this, showMsg, duration);
    }

    /**
     * 展示 Toast 消息提示
     *
     * @param showMsg 展示信息
     */
    protected void showRightToast(String showMsg) {
        Toast.showXToast(this, R.drawable.icon_toast_right, showMsg);
    }

    /**
     * 展示 Toast 消息提示
     *
     * @param showMsg 展示信息
     */
    protected void showErrorToast(String showMsg) {
        Toast.showXToast(this, R.drawable.icon_toast_error, showMsg);
    }

    /**
     * 展示 ImageToast 消息提示
     *
     * @param showMsg  展示信息
     * @param duration 展示Toast的时间长短，取值：{@code Toast.LENGTH_SHORT}(2s)、{@code Toast.LENGTH_LONG}(3.5s)
     */
    protected void showErrorLongToast(String showMsg, int duration) {
        Toast.showXToast(this, R.drawable.icon_toast_error, showMsg, duration);
    }

    /**
     * 展示 ImageToast 消息提示
     *
     * @param drawableResId 展示图片
     * @param showMsg       展示信息
     * @param duration      展示Toast的时间长短，取值：{@code Toast.LENGTH_SHORT}(2s)、{@code Toast.LENGTH_LONG}(3.5s)
     */
    protected void showImageToast(int drawableResId, String showMsg, int duration) {
        Toast.showXToast(this, drawableResId, showMsg, duration);
    }

    // ============================================================================== ProgressDialog

    /**
     * 展示加载弹窗，创建一个点击Dialog外侧就可取消的弹窗
     *
     * @param loadingStr 展示的信息
     */
    protected void showProgressDialog(String loadingStr) {
        showProgressDialog(loadingStr, true, true);
    }

    /**
     * 展示加载弹窗，创建一个可取消的弹窗
     * <P>用于在点击外侧不可消失但是点击返回键可消失的场景下，这种场景需要将isOutsideCanceled设置为False即可
     *
     * @param loadingStr        提示语
     * @param isOutsideCanceled 点击弹窗外侧是否可关闭Dialog
     */
    protected void showProgressDialog(String loadingStr, boolean isOutsideCanceled) {
        // 点击弹窗外侧是否可以消失
        showProgressDialog(loadingStr, true, isOutsideCanceled);
    }

    /**
     * 展示加载框
     *
     * @param loadingStr        加载框中提示内容
     * @param isCancel          弹窗是否可关闭（总开关），如果为false弹窗无法关闭，返回和点击Dialog外侧都无法取消
     * @param isOutsideCanceled 点击弹窗外是否可关闭弹窗，isCancel优先，如果isCancel为true，此参数才有效
     */
    protected void showProgressDialog(String loadingStr, boolean isCancel, boolean isOutsideCanceled) {

        if (!isFinishing()) {
            // 先将Dialog移除
            removeProgressDialog();

            // 创建Dialog弹窗
            progressDialog = new ProgressDialog(this, R.style.loading_dialog);
            progressDialog.setIndeterminate(true);
            progressDialog.setCancelable(isCancel);
            progressDialog.setCanceledOnTouchOutside(isOutsideCanceled);
            progressDialog.show();

            // 设置Dialog展示的内容View
            View views = LayoutInflater.from(this).inflate(R.layout.view_loading_dialog, null);
            TextView loading_tv_content = views.findViewById(R.id.loading_tv_content);
            loading_tv_content.setText(loadingStr);
            progressDialog.setContentView(views);

        }

    }

    /**
     * 移除加载框
     */
    protected void removeProgressDialog() {
        if (progressDialog != null) {
            if (progressDialog.isShowing() && !isFinishing()) {
                progressDialog.dismiss();
                progressDialog = null;
            }
        }
    }

    // ====================================================================================== 软键盘

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View focusView = getCurrentFocus();
            if (ScreenUtils.isShouldHideInput(focusView, ev)) {
                InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (inputMethodManager != null) {
                    inputMethodManager.hideSoftInputFromWindow(focusView.getWindowToken(), 0);
                }
            }
            return super.dispatchTouchEvent(ev);
        }
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return super.onTouchEvent(ev);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ActivityManager.getInstance().killActivity(this);
    }


}
